var _ = require('underscore')
var Movie =require('../models/movie')//../上层目录  ./当前目录
var Comment =require('../models/comment')
var Category = require('../models/category')
var fs = require('fs')
var path = require('path')

//list page
exports.movielist = function(req, res){
	Movie.fetch(function(err, movies){//这个fetch 是在shemale里面置自定的函数
		console.log("/admin/list   movies")
		if (err) {
			console.log(err)
		}
		res.render('list',{
		title:'imooc 列表页',
		movies:movies
	})
	})
	
}

//detail page
exports.detail=function(req, res){
	console.log("/movie/ id="+id)
	var id= req.params.id
	Movie.findById(id, function(err, movie){
		Movie.update({_id:id},{$inc:{pv:1}},function(err){
			if (err) {
				console.log(err)
			}
		})//访客功能
		Comment
			.find({movie:id})
			.populate('from','name')//from里面的id去user里面查对应的名称，返回过来.不过这里应该判断下name是否为空
			.populate('reply.from reply.to','name')
			.exec(
					function(err,comments){
						console.log(comments)
						try{
						res.render('detail',{
						title: 'imooc' + movie.title,
						movie: movie,
						comments:comments
							})
						}catch(e){console.log(e )}	
					}
				)		
	})
	
}

//admin page
exports.new=function(req, res){
	Category.find({},function(err,categories){
		res.render('admin',{
			title:'imooc 后台录入页',
			categories:categories,
			movie: {}
		})
	})
	
}


//admin update movie
exports.update=function(req,res){
	var id = req.params.id
	console.log("id="+id)
	if (id) {
		Movie.findById(id, function(err, movie){
			Category.find({},function(err,categories){
				res.render('admin',{//函数render里面的参数是模板的文件名
				title:'imooc 后台更新页',
				movie: movie,
				categories: categories
				})
			})
			
		})
	}
}
//admin poster
exports.savePoster = function(req,res,next){
	var posterData = req.files.uploadPoster
	var filePath = posterData.path
	var originalFilename = posterData.originalFilename

	console.log(req.files)
	if(originalFilename){
		fs.readFile(filePath,function(err,data){
			var timestamp=Date.now()
			var type= posterData.type.split('/')[1]
			var poster = timestamp+'.'+type
			var newPath=path.join(__dirname,'../../','/public/upload/'+ poster)

			fs.writeFile(newPath,data,function(err){
				req.poster=poster
				next()
			})
		})
	}else{
		next()
	}
}
//admin post movie
exports.save = function(req, res){//我曹，搞了这么久，居然是req和res写反了，我勒个去~~~写代码真的可以把人给气死
	console.log("here")
	var id = req.body.movie._id
	var movieObj = req.body.movie
	var _movie

	if(req.poster){
		movieObj.poster = req.poster
	}

	if (id) {
		Movie.findById(id,function(err, movie){
			if (err) {
				console.log(err)
			}
			_movie =_.extend(movie,movieObj)
			_movie.save(function(err,movie){
				if (err) {
					console.log(err)
				}

				res.redirect('/movie/'+movie._id)
			})
		})
	}
	else{
		_movie = new Movie(movieObj)

		var categoryId=movieObj.category
		var categoryName=movieObj.categoryName

		_movie.save(function(err,movie){
			if (err) {
				comsole.log(err)
			}
			if (categoryId) {
				Category.findById(categoryId,function(err,category){
					category.movies.push(movie._id)//这里容易混了，movie和_movie

					category.save(function(err,category){
						res.redirect('/movie/' + movie._id)
					})
				})	
			}else if(categoryName){
				var category = new Category({
					name:categoryName,
					movies:[movie._id]
				})

				category.save(function(err,category){
					movie.categoryName=category._id
					movie.save(function(err,movie){
						res.redirect('/movie/' + movie._id)
					})
				})
			}
		})
	}
}//说实话这部分的逻辑，我真的有点混了，特别是几个movie对象

//delete
exports.del = function(req,res){
	var id=req.query.id
	console.log('id:'+id)
	if(id){
		Movie.remove({
			_id:id
		},function(err,movie){
			if(err){
				console.log(err);
			}else{
				res.json({
					success:1
				})
			}
		})
	}
}